<template>
	<div class="flex justify-between items-center">
		<router-link :to="handleRedirect()" class="no-underline cursor-pointer">
			<up-title
				:title="selectedCategory.title"
				:titleT="selectedCategory.titleT"
				:image="selectedCategory.labelIcon"
				:icon="selectedCategory.icon"
				:iconColor="iconColor"
				class="cursor-pointer" />
		</router-link>
		<div class="flex relative">
			<router-link
				:to="handleRedirect()"
				v-if="isPC"
				class="mr-[10px] h-7 px-4 rounded-lg bg-bg-3 flex items-center app-bg-react text-t-2 no-underline cursor-pointer"
				@click="handleRedirect()">
				{{ $t('action.seeAll') }}
			</router-link>
			<div class="flex items-center gap-[2px]">
				<div
					class="w-9 h-7 rounded-l-full bg-bg-3 flex justify-center items-center app-bg-react myPrev"
					:class="data?.labelCode || type">
					<base-icon name="back"></base-icon>
				</div>
				<div
					class="w-9 h-7 rounded-r-full bg-bg-3 flex justify-center items-center app-bg-react myNext"
					:class="data?.labelCode || type">
					<base-icon name="go"></base-icon>
				</div>
			</div>
		</div>
	</div>
	<div class="slide-container">
		<swiper
			:slidesPerView="pageSize"
			:slidesPerGroup="slidesPerGroup"
			:spaceBetween="10"
			:allowTouchMove="!isPC"
			@slideChange="swiperChange"
			:navigation="{
				enabled: true,
				prevEl: `.myPrev.${data?.labelCode || type}`,
				nextEl: `.myNext.${data?.labelCode || type}`
			}"
			:freeMode="false"
			:modules="modules"
			:touchMoveStopPropagation="true"
			:breakpoints="{
				320: { slidesPerView: 3 },
				530: { slidesPerView: 3.5 },
				830: { slidesPerView: 4.5 },
				1030: { slidesPerView: 5.5 },
				1230: { slidesPerView: 6.5 },
				1430: { slidesPerView: 7.5 },
				1630: { slidesPerView: 8.5 }
			}"
			class="mySwiper"
			:class="data ? data.labelCode : type">
			<swiper-slide v-for="item in list" :key="item.id">
				<router-link :to="handleRouterLink(item)" class="w-full app-hover-offset">
					<base-image
						v-if="type === 'provider'"
						class="provider-img"
						:class="item.fullGameName || item.gameKey ? 'cursor-pointer' : ''"
						:src="item.iconPath"
						default="placeholder.svg"
						type="network"></base-image>
					<base-image
						v-else
						class="rounded-lg w-full h-full object-cover align-bottom cursor-pointer"
						:class="item.fullGameName || item.gameKey ? 'cursor-pointer' : ''"
						:src="formatGameIconUrl(item)"
						default="placeholder-higher.svg"
						type="network"></base-image>
				</router-link>
			</swiper-slide>
			<div v-show="hasNext && isPC" class="fake-swiper"></div>
		</swiper>
	</div>
</template>
<script lang="ts">
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue'
import {
	getHomeGameRecommendList,
	getAllProviderList,
	gameRecentPlayedList,
	getProviderBySlug
} from '@/api/other.ts'
import { BaseImage, BaseIcon, BaseRouter } from '@/components/base'
import UpTitle from '@/components/up/up-title/index.vue'
import { CASINO_LIST, PROVIDER_LIST, PLAYER_RECENT_LIST } from '@/constants'
import { setItem, getItem, isPC, t } from '@/utils'
import { Autoplay, FreeMode, Navigation } from 'swiper/modules'
import { watch } from 'vue'
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/navigation'
import { isDesktop } from '@/hooks/useIsPC.ts'
import { useAccountStore, useAppStore } from '@/store'
import { LangGameFormat } from '@/enums'
import { genOriginalRoute } from '@/components/slots/utils.ts'
export default {
	props: {
		type: {
			type: String,
			default: 'slots'
		},
		seeAll: {
			type: Boolean,
			default: false
		},
		titleT: {
			type: String,
			default: 'slotsrecommends.title'
		},
		iconColor: {
			type: String,
			default: 'var(--color-primary)'
		},
		icon: {
			type: String,
			default: 'slots2'
		},
		pageSize: {
			type: Number,
			default: isPC() ? 8.5 : 3
		},
		slidesPerGroup: {
			type: Number,
			default: isPC() ? 8 : 3
		},
		data: {
			type: Object
		},
		gameData: {
			type: Object
		}
	},
	components: {
		Swiper,
		SwiperSlide,
		BaseImage,
		BaseIcon,
		UpTitle,
		BaseRouter
	},
	data() {
		return {
			isPC: isDesktop,
			currentIndex: 0,
			swiper: null,
			hasPrev: false,
			hasNext: true,
			list: [] as Record<string, any>[],
			total: 0,
			category: {
				casino: {
					title: '',
					titleT: 'casino.title',
					icon: 'slots2',
					labelIcon: '',
					routerName: 'casino'
				},
				provider: {
					title: '',
					titleT: 'casinoAll.providers',
					icon: 'provider',
					labelIcon: '',
					routerName: 'casinoProvider'
				},
				providerBySlug: {
					title: '',
					titleT: 'casinoAll.providers',
					icon: 'provider',
					labelIcon: '',
					routerName: 'casinoProviderDetail'
				},
				playerRecent: {
					title: '',
					titleT: 'casinoAll.recent',
					icon: 'history',
					labelIcon: '',
					routerName: 'recent'
				}
			},
			selectedCategory: {
				title: '',
				titleT: '',
				icon: '',
				labelIcon: '',
				id: 'casino',
				routerName: ''
			},
			locale: useAppStore().lang,
			accountStore: useAccountStore(),
			isLogin: useAccountStore().isLogin
		}
	},
	setup() {
		watch(
			() => [useAppStore().lang, useAccountStore().isLogin],
			function () {
				// @ts-ignore
				this?.initAll()
				// @ts-ignore
				//this.locale = value[0]
			}
		)
		return {
			modules: [Autoplay, FreeMode, Navigation]
		}
	},
	watch: {
		gameData() {
			this.initProviderSlugData()
		},
		data() {
			this.init()
		}
	},
	mounted() {
		this.initAll()
		window.addEventListener('resize', this.hasNextPrevEvent)
	},
	methods: {
		initAll() {
			if (this.data) {
				this.init()
			} else if (this.gameData) {
				this.initProviderSlugData()
			} else {
				if (this.type !== 'providerBySlug') {
					this.getList()
				}
			}
		},
		init() {
			this.selectedCategory.title = this.data?.labelName
			this.selectedCategory.icon = 'slots2'
			this.selectedCategory.labelIcon = this.data?.labelIcon
			this.selectedCategory.id = this.data?.tagSlug

			this.list = this.data?.games
			this.total = this.list.length

			if (this.total >= 24) {
				let obj = {
					gameIcon: `https://d11njdywhf5zo.cloudfront.net/see-more-${useAppStore().lang}.svg`,
					isSeeMore: true,
					id: this.data?.tagSlug
				}
				this.list.push(obj)
			}
			this.hasNextPrevEvent()
		},
		async initProviderSlugData() {
			this.selectedCategory = (this.category[this.type as keyof typeof this.category] ||
				this.category.casino) as any
			const result = await getProviderBySlug({
				page: 1,
				pageSize: 24,
				developerSlug: this.gameData?.developerSlug
			})
			this.selectedCategory.title = this.gameData?.developerName
			this.selectedCategory.id = this.gameData?.developerSlug
			this.list = Array.from(result.data.items || [])
			if (this.type !== 'provider') {
				this.total = this.list.length
				if (this.total >= 24) {
					let obj = {
						gameIcon: `https://d11njdywhf5zo.cloudfront.net/see-more-${useAppStore().lang}.svg`,
						isSeeMore: true,
						slug: this.type
					}
					this.list.push(obj)
				}

				this.hasNextPrevEvent()
			}
		},
		async getList() {
			let isLogin = this.accountStore.isLogin
			if (isLogin) {
				this.category.casino.title = t('casinoAll.recent')
				this.category.casino.icon = 'history'
			}

			this.selectedCategory = (this.category[this.type as keyof typeof this.category] ||
				this.category.casino) as any

			let result = []
			if (this.type === 'casino') {
				this.list = Array.from(getItem(CASINO_LIST) || [])
				result = await getHomeGameRecommendList({ page: 1, pageSize: 24 })
				setItem(CASINO_LIST, result.data.items)
			} else if (this.type === 'playerRecent') {
				this.list = Array.from(getItem(PLAYER_RECENT_LIST) || [])
				result = await gameRecentPlayedList({ page: 1, pageSize: 24 })
				setItem(PLAYER_RECENT_LIST, result.data.items)
			} else if (this.type === 'providerBySlug') {
			} else {
				this.list = Array.from(getItem(PROVIDER_LIST) || [])
				result = await getAllProviderList({ page: 1, pageSize: 24 })
				setItem(PROVIDER_LIST, result.data.items)
			}
			this.list = Array.from(result.data.items || [])
			if (this.type !== 'provider') {
				this.total = this.list.length
				if (this.total >= 24) {
					let obj = {
						gameIcon: `https://d11njdywhf5zo.cloudfront.net/see-more-${useAppStore().lang}.svg`,
						isSeeMore: true,
						slug: this.type
					}
					this.list.push(obj)
				}
				this.hasNextPrevEvent()
			}
		},
		hasNextPrevEvent() {
			let windowWidth = window.innerWidth
			let pageSizePreview = this.pageSize
			if (windowWidth < 1630) {
				pageSizePreview = 7.5
			} else if (windowWidth < 1430) {
				pageSizePreview = 6.5
			} else if (windowWidth < 1030) {
				pageSizePreview = 5.5
			} else if (windowWidth < 830) {
				pageSizePreview = 4.5
			} else if (windowWidth < 530) {
				pageSizePreview = 3.5
			} else if (windowWidth < 320) {
				pageSizePreview = 3
			}
			this.hasNext = this.currentIndex + pageSizePreview < this.total + 0.5
			this.hasPrev = this.currentIndex > 0
		},
		onPrev() {
			let swiper
			if (this.data) {
				swiper = document.querySelector(`.swiper.${this.data.labelCode}`) as any
			} else {
				swiper = document.querySelector(`.swiper.${this.type}`) as any
			}
			this.currentIndex = this.currentIndex - this.pageSize
			swiper.swiper.slideTo(this.currentIndex)
			this.hasNextPrevEvent()
		},
		onNext() {
			let swiper
			if (this.data) {
				swiper = document.querySelector(`.swiper.${this.data.labelCode}`) as any
			} else {
				swiper = document.querySelector(`.swiper.${this.type}`) as any
			}
			this.currentIndex = this.currentIndex + this.pageSize
			swiper.swiper.slideTo(this.currentIndex)
			this.hasNextPrevEvent()
		},
		swiperChange(event: any) {
			this.hasNext = event.isEnd ? false : true
		},
		handleRedirect() {
			if (this.data) {
				return {
					name: 'casinoTags',
					params: {
						locale: this.locale,
						id: this.selectedCategory.id
					}
				}
			} else if (this.type === 'providerBySlug') {
				return {
					name: 'casinoProviderDetail',
					params: { id: this.selectedCategory.id, locale: this.locale }
				}
			} else {
				return {
					name: this.selectedCategory.routerName,
					params: {
						locale: this.locale
					}
				}
			}
		},

		handleRouterLink(item: any) {
			if (item.category === 3) {
				//original
				return genOriginalRoute(item)
			} else if (item.isSeeMore) {
				if (this.data) {
					return {
						name: 'casinoTags',
						params: { locale: this.locale, id: item.id }
					}
				} else if (this.type === 'providerBySlug') {
					return {
						name: 'casinoProviderDetail',
						params: { id: this.selectedCategory.id, locale: this.locale }
					}
				} else {
					return {
						name: this.selectedCategory.routerName,
						params: { locale: this.locale }
					}
				}
			} else if (this.type === 'provider') {
				return {
					name: 'casinoProviderDetail',
					params: { id: item.slug, locale: this.locale }
				}
			} else {
				return { name: 'casinoDetail', params: { id: item.slug || item.id, locale: this.locale } }
			}
		},
		formatGameIconUrl(item: any) {
			let lang = useAppStore().lang

			let formatLang = LangGameFormat[lang]

			let icon
			if (item.gameEntranceIcon) {
				icon = item.gameEntranceIcon[formatLang] || item.gameIcon
			} else {
				icon = item.gameIcon
			}

			return icon
			//return item.gameEntranceIcon.en_US ? item.gameEntranceIcon.en_US : item.gameIcon
		}
	}
}
</script>
<style>
.swiper {
	width: 100%;
	height: 100%;
}
.mySwiperAutoPlay .swiper-wrapper {
	transition-timing-function: linear;
}
.swiper-wrapper {
	transition: all 0.3s;
}
.swiper-slide {
	text-align: center;
	font-size: 18px;
	color: black;
	width: auto;
	/* Center slide text vertically */
	display: flex;
	justify-content: center;
	align-items: center;
}

.swiper-slide img {
	display: block;
	object-fit: cover;
}

.provider-img {
	width: 100%;
	height: 60px !important;
	background-color: #212834;
	border-radius: 8px;
	padding: 10px 18px;
	object-fit: contain !important;
}
.fake-swiper {
	position: absolute;
	right: 0;
	top: 10px;
	bottom: 0;
	cursor: pointer;
	background: linear-gradient(-90deg, rgba(8, 8, 8, 0.898), #08080800);
	width: 75px;
	transition: 0.3s opacity;
	z-index: 1;
	border-top-left-radius: 8px;
	border-bottom-left-radius: 8px;
}
@media (max-width: 768px) {
	.provider-img {
		height: 50px !important;
		width: 100% !important;
	}
}
</style>
